package com.zou.lotterylucky.activity

import android.annotation.SuppressLint
import android.app.DatePickerDialog
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import com.android.volley.toolbox.Volley
import com.chad.library.adapter.base.BaseSectionQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.chad.library.adapter.base.entity.SectionEntity
import com.jakewharton.rxbinding3.view.clicks
import com.qmuiteam.qmui.widget.QMUITabSegment
import com.qmuiteam.qmui.widget.dialog.QMUIDialog
import com.v2.request.RequestCenter
import com.v2.utils.okhttp.OkHttpRequestCallback
import com.zou.lotterylucky.LotteryApp
import com.zou.lotterylucky.R
import com.zou.lotterylucky.utils.*
import kotlinx.android.synthetic.main.activity_total.*
import kotlinx.android.synthetic.main.activity_total.rcv
import kotlinx.android.synthetic.main.activity_total.topbar
import org.json.JSONArray
import org.json.JSONObject
import woyou.aidlservice.jiuiv5.ICallback
import java.text.DecimalFormat
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit

/**
 * 总单
 */
class TotalActivity : BaseActivity() {
    lateinit var adapter: DanChangAdapter

    @SuppressLint("SimpleDateFormat")
    private val dateFormatter = SimpleDateFormat("yyyy-MM-dd")
    private var currentEndTime = 0L
    var printing = false//是否正在打印中

    @SuppressLint("CheckResult")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        TLog.v("enter TotalActivity")
        setContentView(R.layout.activity_total)
        val set = mutableListOf<MySection>()
        topbar.setTitle(R.string.zongdan)
        topbar.addLeftBackImageButton().setOnClickListener { onBackPressed() }

        adapter = DanChangAdapter(set)
        rcv.layoutManager = LinearLayoutManager(this)
        rcv.adapter = adapter

        AidlUtil.instance.getTime("yyyy-MM-dd", object : TimeCallBack {
            override fun onError(msg: String?) {
            }

            override fun onSuccess(time: String?) {
                textDate.text = time
            }
        })
//        currentEndTime = ClockUtil.getEndTime(this, System.currentTimeMillis())
//        textDate.text = dateFormatter.format(currentEndTime)

        var cal = Calendar.getInstance()

        val dateSetListener =
            DatePickerDialog.OnDateSetListener { view, year, monthOfYear, dayOfMonth ->
                cal.set(Calendar.YEAR, year)
                cal.set(Calendar.MONTH, monthOfYear)
                cal.set(Calendar.DAY_OF_MONTH, dayOfMonth)

                textDate.text = dateFormatter.format(cal.time)
                initData()
            }

        textDate.clicks().throttleFirst(1000, TimeUnit.MILLISECONDS)
            .subscribe {
                DatePickerDialog(
                    this, dateSetListener,
                    cal.get(Calendar.YEAR),
                    cal.get(Calendar.MONTH),
                    cal.get(Calendar.DAY_OF_MONTH)
                ).show()
            }

        tabs.addTab(QMUITabSegment.Tab(("KORSOU")))
        tabs.addTab(QMUITabSegment.Tab(("FLAMINGO")))
        tabs.addTab(QMUITabSegment.Tab(("DIARIO")))
        tabs.addTab(QMUITabSegment.Tab(("ST")))
        tabs.addOnTabSelectedListener(object : QMUITabSegment.OnTabSelectedListener {
            override fun onDoubleTap(index: Int) {
            }

            override fun onTabReselected(index: Int) {
            }

            override fun onTabUnselected(index: Int) {
            }

            override fun onTabSelected(index: Int) {
                selectData(index)
            }
        })

        tabs.selectTab(0)
        initData()

        btnPrint.clicks().throttleFirst(600, TimeUnit.MILLISECONDS)
            .subscribe {
                if (printing) {
                    return@subscribe
                }
                if (!isNetworkAvailable(this)) {
                    ToastUtil.showToast(this, getString(R.string.internet_fail))
                    return@subscribe
                }
                if (!AidlUtil.instance.isConnect) {
                    ToastUtil.showToast(this, R.string.weilianjiadayinfuwu)
                    return@subscribe
                }

                AidlUtil.instance.getTime("dd-MM-yyyy HH:mm:ss", object : TimeCallBack {
                    override fun onError(msg: String?) {

                    }

                    override fun onSuccess(time: String?) {
                        if (time != null) {
                            goToPrint(time)
                        }
                    }
                })
            }
    }

    /**
     * 去打印
     * @param timeNow 当前时间
     */
    private fun goToPrint(timeNow: String) {
        printing = true
        AidlUtil.instance.printATotal(
            timeNow,
            allData,
            textDate.text.toString(),
            object : ICallback.Stub() {
                override fun onRunResult(isSuccess: Boolean) {
                }

                override fun onPrintResult(code: Int, msg: String?) {
                    printing = false
                    runOnUiThread {
                        if (code == 0) {//打印成功

                            val dialog =
                                QMUIDialog.MessageDialogBuilder(this@TotalActivity)
                                    .setMessage(R.string.dayin_chenggong)
                                    .addAction(
                                        R.string.confirm
                                    ) { p0, _ ->
                                        p0.dismiss()
                                    }
                                    .create()
                            dialog.setCancelable(false)
                            dialog.show()
                        } else {//打印失败
                            val dialog =
                                QMUIDialog.MessageDialogBuilder(this@TotalActivity)
                                    .setMessage(R.string.dayinshibai)
                                    .addAction(
                                        R.string.confirm
                                    ) { p0, _ ->
                                        p0.dismiss()
                                    }
                                    .create()
                            dialog.setCancelable(false)
                            dialog.show()
                        }
                    }
                }

                override fun onReturnString(result: String?) {
                }

                override fun onRaiseException(code: Int, msg: String?) {
                }
            })
    }

    private fun filterData(
        type: Int,
        pool: Boolean,
        data: List<BetCountEntity>,
        belongTo: String
    ): MutableList<MySection> {
        val d = data.filter {
            it.type == type && it.pool == pool
        }
        if (d.isEmpty()) return mutableListOf()
        return d.groupBy {
            it.num
        }.mapValues {
            it.value.sumByDouble { bet ->
                bet.money
            }
        }.map {
            MySection(BetCountEntity(it.key.toString(), it.key, it.value, pool, type, belongTo))
        }.sortedByDescending { it.t.num }
            .toMutableList()
    }

    private var allData: MutableList<MySection> = mutableListOf()

    @SuppressLint("CheckResult", "SimpleDateFormat")
    private fun initData() {
        val requestQueue = Volley.newRequestQueue(this)

        val startTimeStr = textDate.text.toString() + " " + "00:00:00"
        val startTimeDate = DateUtil.localToUTC(startTimeStr)
        val endTimeStr = textDate.text.toString() + " " + "23:59:59"
        val endTimeDate = DateUtil.localToUTC(endTimeStr)

//        val url = Constants.SERVER_URL + "getOrders"
//        val params = JSONObject()
//        params.put("machine_number", SPUtils[this, "username", ""])
////        params.put("date", textDate.text)
//        params.put("start", SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(startTimeDate))
//        params.put("end", SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(endTimeDate))

        RequestCenter.appGetOrders(
            SPUtils["username", ""] as String,
            "",
            "",
            SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(startTimeDate),
            SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(endTimeDate),
            object : OkHttpRequestCallback {
                override fun onSuccess(response: String?) {
                    val data = JSONObject(response).getJSONArray("data")
                    allData = mutableListOf()
                    val map = mutableListOf<BetCountEntity>()
                    for (i in 0 until data.length()) {
                        if (data.getJSONObject(i).getInt("is_deleted") == 0) {
                            val betsData = data.getJSONObject(i).getJSONArray("bet_numbers")
                            for (j in 0 until betsData.length()) {
                                val bet = BetCountEntity()
                                val betData = betsData.getJSONObject(j)
                                bet.num =
                                    betData.getString("bet_number").replace("P", "").trim().toInt()
                                bet.money = betData.getDouble("bet_money")
                                bet.pool = betData.getInt("is_pool") == 1
                                bet.type =
                                    betData.getString("bet_number").replace("P", "").trim().length
                                if (bet.type == 1) {
                                    bet.type = 2
                                }
                                bet.belongTo = data.getJSONObject(i).getString("belong_to")
                                map.add(bet)
                            }
                        }
                    }

                    val regions = arrayOf("K", "F", "D", "S")
                    for (i in regions) {
                        val findedElement = map.filter { it.belongTo.contains(i) }
                        allData.add(MySection(true, LotteryApp.getTitleSimple(i)))
                        allData.addAll(filterData(4, false, findedElement, i))
                        allData.addAll(filterData(3, false, findedElement, i))
                        allData.addAll(filterData(2, false, findedElement, i))
                        allData.addAll(filterData(4, true, findedElement, i))
                        allData.addAll(filterData(3, true, findedElement, i))
                        allData.addAll(filterData(2, true, findedElement, i))
                    }

                    if (tabs.selectedIndex == 0) {
                        selectData(0)
                    } else {
                        tabs.selectTab(0)
                    }
                }

                override fun onFailure(error: String?) {
                    TLog.net("getOrders failure:$error")
                }
            }
        )

//        val request = JsonObjectRequest(Request.Method.POST, url, params, { response ->
//            try {
//                val status = response.get("status") as Int
//                if (status == 200 && !response.isNull("data")) {
//                    val data = response.get("data") as JSONArray
//                    allData = mutableListOf()
//                    val map = mutableListOf<BetCountEntity>()
//                    for (i in 0 until data.length()) {
//                        if (data.getJSONObject(i).getInt("is_deleted") == 0) {
//                            val betsData = data.getJSONObject(i).getJSONArray("bet_numbers")
//                            for (j in 0 until betsData.length()) {
//                                val bet = BetCountEntity()
//                                val betData = betsData.getJSONObject(j)
//                                bet.num =
//                                    betData.getString("bet_number").replace("P", "").trim().toInt()
//                                bet.money = betData.getDouble("bet_money")
//                                bet.pool = betData.getInt("is_pool") == 1
//                                bet.type =
//                                    betData.getString("bet_number").replace("P", "").trim().length
//                                if (bet.type == 1) {
//                                    bet.type = 2
//                                }
//                                bet.belongTo = data.getJSONObject(i).getString("belong_to")
//                                map.add(bet)
//                            }
//                        }
//                    }
//
//                    val regions = arrayOf("K", "F", "D", "S")
//                    for (i in regions) {
//                        val findedElement = map.filter { it.belongTo.contains(i) }
//                        allData.add(MySection(true, LotteryApp.getTitleSimple(i)))
//                        allData.addAll(filterData(4, false, findedElement, i))
//                        allData.addAll(filterData(3, false, findedElement, i))
//                        allData.addAll(filterData(2, false, findedElement, i))
//                        allData.addAll(filterData(4, true, findedElement, i))
//                        allData.addAll(filterData(3, true, findedElement, i))
//                        allData.addAll(filterData(2, true, findedElement, i))
//                    }
//
//                    if (tabs.selectedIndex == 0) {
//                        selectData(0)
//                    } else {
//                        tabs.selectTab(0)
//                    }
//                }
//
//            } catch (e: JSONException) {
//                e.printStackTrace()
//            }
//        }, { error -> error.printStackTrace() })
//        requestQueue?.add(request)
    }

    private fun selectData(selectedIndex: Int) {
        val moneyFormat = DecimalFormat("0.00")

        textTotal.text =
            "${getString(R.string.zongjine_dot)}${
                moneyFormat.format(
                    allData.filter {
                        when (selectedIndex) {
                            0 -> !it.isHeader && it.t.belongTo.contains("K")
                            1 -> !it.isHeader && it.t.belongTo.contains("F")
                            2 -> !it.isHeader && it.t.belongTo.contains("D")
                            3 -> !it.isHeader && it.t.belongTo.contains("S")
                            else -> false
                        }
                    }.sumByDouble { a -> a.t.money }
                )
            }"

        textAll.text =
            "一共总金额：${
                moneyFormat.format(
                    allData.filter { !it.isHeader }.sumByDouble { a -> a.t.money }
                )
            }"

        adapter.replaceData(allData.filter {
            when (selectedIndex) {
                0 -> !it.isHeader && it.t.belongTo.contains("K")
                1 -> !it.isHeader && it.t.belongTo.contains("F")
                2 -> !it.isHeader && it.t.belongTo.contains("D")
                3 -> !it.isHeader && it.t.belongTo.contains("S")
                else -> false
            }
        })
    }
}

class BetCountEntity(
    var srcNumber: String = "",
    var num: Int = 0,
    var money: Double = 0.0,
    var pool: Boolean = false,
    var type: Int = 4,
    var belongTo: String = "",
    var isWinner: Int = 0,
    var rank: Int = 0,
    var prizes: Double = 0.0,
    var createdAt: String = ""
) {
    fun getNumber(): String {
        return String.format("%0${type}d", num) + if (pool) " P" else ""
    }
}

class MySection : SectionEntity<BetCountEntity> {
    constructor(isHeader: Boolean, header: String) : super(isHeader, header) {}
    constructor(t: BetCountEntity) : super(t) {}
}

class DanChangAdapter(data: MutableList<MySection>) :
    BaseSectionQuickAdapter<MySection, BaseViewHolder>(
        R.layout.item_bet_count,
        R.layout.item_total_title,
        data
    ) {
    val moneyFormat = DecimalFormat("0.00")

    override fun convertHead(helper: BaseViewHolder, item: MySection) {
        helper.setText(R.id.textTitle, item.header)
    }

    override fun convert(helper: BaseViewHolder, it: MySection) {
        val item = it.t
        helper.setText(R.id.textNum, item.getNumber())
            .setText(R.id.textMoney, moneyFormat.format(item.money))
            .setText(R.id.textPool, if (item.pool) "Pool" else "")
    }
}
